package test;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/ai")
@Slf4j
public class ChatController {

    @Value("${ai.config.deepseek.apiKey}")
    private String apiKey;

    @Value("${ai.config.deepseek.baseUrl}")
    private String apiUrl;

    private final ExecutorService executorService = Executors.newCachedThreadPool();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ChatService chatService;

    public ChatController(ChatService chatService) {
        this.chatService = chatService;
    }

    @PostConstruct
    public void init() {
        Assert.hasText(apiKey, "API key must not be empty");
        Assert.hasText(apiUrl, "API URL must not be empty");
    }

    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chat(@RequestParam("message") String question) {
        log.info("开始处理流式问答请求，问题：{}", question);
        SseEmitter emitter = new SseEmitter(-1L);
        
        executorService.execute(() -> {
            try {
                chatService.streamChat(question, emitter);
                log.info("流式问答结束，问题：{}", question);
                emitter.complete();
            } catch (Exception e) {
                log.error("处理流式问答请求时发生错误，问题：{}，错误：{}", question, e.getMessage(), e);
                emitter.completeWithError(e);
            }
        });
        
        return emitter;
    }
}
